import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Divider, Timeline, Row, Col,Avatar,InputNumber, Input, DatePicker, } from 'antd';
const FormItem = Form.Item;
const ButtonGroup = Button.Group;
const { TextArea } = Input;
const moment = require('moment');
import API from '../../../api/files/index';
import {API_DOMAIN} from "../../../utils/constants";
import {Button, Form, message} from "antd/lib/index";

class ShareRecord extends Component {
  constructor (props) {
    super(props);
    this.state = {
      share: props.share,
      records: [],
      settings: "",
    };
      this.handleCancel = this.handleCancel.bind(this);
  }

  getDetail = async (shareId) => {
    const params = {
      id: shareId,
      level: 'entity',
      type: 'share',
      sortByCreatedAt:'DESC',
    };
    const response = await API.getOperateRecords(params);
    const { code, data } = response;
    if (code === 1) {
      this.setState({
        records: data,
      });
    }
  }

  getShareSettings = async (params) => {
    const response = await API.viewShare(params);
    const { code, data } = response;
    if (code === 1) {
      this.setState({
        settings: data,
      });
    }
  }

    // refresh = async () => {
    //     const { id } = this.state.share;
    //     const response = await API.refreshFlie(id);
    //     const { code } = response;
    //     if (code === 1) {
    //         this.props.getShareList();
    //     }
    // }

  componentDidMount ()  {
    const { id } = this.state.share;
    const params = {
      shareId: id,
      isSigned: true,
    };
    this.getDetail(id);
    this.getShareSettings(params);
  }

    componentWillReceiveProps (nextProps) {
      console.log(nextProps);
        this.setState({
            share: nextProps.share,
        });
    }

    handleCancel() {
        const { id } = this.state.share;

        var parentElements = document.getElementsByClassName("demo-content");
        var sonElements = parentElements[0].children[1].getElementsByClassName("ant-collapse")[0].children;
            for (let i = 0; i < sonElements.length; i++) {
               var son = sonElements[i].className.indexOf('ant-collapse-item-active');
               if(son>0){
                   sonElements[i].children[0].setAttribute('aria-expanded','false');
                   console.log(sonElements[i].children[0].getAttribute('aria-expanded'));

                   var sonEval = sonElements[i].children[1].getAttribute("class").replace("ant-collapse-content ant-collapse-content-active","ant-collapse-content ant-collapse-content-inactive");
                   sonElements[i].children[1].setAttribute("class",sonEval);
                   // var classVal = sonElements[i].getAttribute("class");
                   // classVal = classVal.replace("ant-collapse-item ant-collapse-item-active","ant-collapse-item");
                   // sonElements[i].setAttribute("class",classVal );
               }
            }
        // this.refresh();
        this.props.getShareList();
    }

    handleSaveShareSettings = async (e) => {
        e.preventDefault();
        const id = this.state.records[0].entity.id;
        this.props.form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const params = {
                    shareId: id,
                    wxTitle: values.wxTitle,
                    wxDescription: values.wxDescription,
                    limited: values.limited || -1,
                    expire: (values.expire && moment(values.expire).format('YYYY-MM-DD HH:mm:ss')) || null,
                    password: values.password,
                };
                const response = await API.modifyShare(params);
                const { code, data } = response;
                if (code === 1) {
                    message.success('修改成功');
                    this.props.getShareList();
                }
            }
        });
        var parentElements = document.getElementsByClassName("demo-content");
        var sonElements = parentElements[0].children[1].getElementsByClassName("ant-collapse")[0].children;
        for (let i = 0; i < sonElements.length; i++) {
            var son = sonElements[i].className.indexOf('ant-collapse-item-active');
            if(son>0){
                sonElements[i].children[0].setAttribute('aria-expanded','false');
                console.log(sonElements[i].children[0].getAttribute('aria-expanded'));

                var sonEval = sonElements[i].children[1].getAttribute("class").replace("ant-collapse-content ant-collapse-content-active","ant-collapse-content ant-collapse-content-inactive");
                sonElements[i].children[1].setAttribute("class",sonEval);
                // var classVal = sonElements[i].getAttribute("class");
                // classVal = classVal.replace("ant-collapse-item ant-collapse-item-active","ant-collapse-item");
                // sonElements[i].setAttribute("class",classVal );
            }
        }
        // this.refresh();
        this.props.getShareList();
    }


    render () {
      const { share, settings } = this.state;
      const { getFieldDecorator } = this.props.form;
      const formItemLayout = {
          labelCol: {
              xs: { span: 24 },
              sm: { span: 5 },
          },
          wrapperCol: {
              xs: { span: 24 },
              sm: { span: 16 },
          },
      };
      const dateTime = share.link.expire == null ?share.link.expire: share.link.expire.slice(0,10);
      const timeMoment = share.link.expire;
      const linkMoment = moment(timeMoment);
      console.log( this.state.settings);
      console.log( this.state.settings.message);
      return (
          <div>
          {
                this.props.visibleOfEdit ?
                  <Form onSubmit={this.handleSaveShareSettings} className="formClass">
                      <FormItem
                          {...formItemLayout}
                          label="可查看次数"
                      >
                          {
                              getFieldDecorator('limited', {
                                  initialValue:`${share.link.limited}`,
                                  rules: [{
                                      pattern: /^[1-9]\d*$/, message: '可查看次数不得小于1',
                                  }],
                              })(<InputNumber style={{width: '100%'}} min={0}/>)
                          }
                      </FormItem>
                      <FormItem
                          {...formItemLayout}
                          label="有效期"
                      >
                          {
                              getFieldDecorator('expire', {
                                  initialValue: linkMoment,
                                  rules: [],
                              })(<DatePicker
                                  showTime
                                  style={{width: '100%'}}
                                  format="YYYY-MM-DD HH:mm:ss"
                                  placeholder="请选择有效期"
                              />)
                          }
                      </FormItem>
                      <FormItem
                          {...formItemLayout}
                          label="查看密码"
                      >
                          {
                              getFieldDecorator('password', {
                                  initialValue:`${share.link.password}`,
                                  rules: [],
                              })(<Input/>)
                          }
                      </FormItem>
                      <FormItem
                          {...formItemLayout}
                          label="分享标题"
                      >
                          {
                              getFieldDecorator('wxTitle', {
                                  initialValue:`${this.state.settings.message==undefined ? "" :this.state.settings.message.title}`,
                                  rules: [],
                              })(<Input/>)
                          }
                      </FormItem>
                      <FormItem
                          {...formItemLayout}
                          label="分享描述"
                      >
                          {
                              getFieldDecorator('wxDescription', {
                                  initialValue:`${this.state.settings.message==undefined? "" :this.state.settings.message.desciption}`,
                                  rules: [],
                              })(<TextArea rows={2}/>)
                          }
                      </FormItem>

                      <FormItem wrapperCol={{span: 16, offset: 7}} style={{marginTop: 24}}>
                          <Button type="primary"  htmlType="submit" onClick={this.handleSaveShareSettings}>保存</Button>
                          &nbsp;&nbsp;&nbsp;
                          <Button type="ghost" onClick={this.handleCancel}>取消</Button>
                      </FormItem>
                  </Form> :
                  <div>
                      <Row>
                          <Col span={12}>
                              <p>
                                  <span style={{fontWeight: 'bold'}}>有效期至：</span><span>{dateTime || '永久有效'}</span><br/>
                                  <span
                                      style={{fontWeight: 'bold'}}>查看次数：</span><span>{share.link.viewed || 0}/{share.link.limited === -1 ? '无限制' : share.link.limited}</span><br/>
                                  <span style={{
                                      fontWeight: 'bold',
                                      marginLeft: 28
                                  }}>密码：</span><span>{share.link.password}</span>
                              </p>
                          </Col>
                          <Col span={12}/>
                      </Row>
                      <Divider/>
                      <Timeline>
                          {
                              this.state.records.length > 0 ? this.state.records.map(record => {
                                  return (
                                      <Timeline.Item>
                                          <Row>
                                              <Col span={10}> <Avatar src={record.operator.avatar}/>
                                                  <span style={{marginLeft: 8}}>{record.createdBy.nickname}</span></Col>
                                              <Col span={14} style={{marginTop: 4}}>
                                                  {
                                                      record.action == 'view' ?
                                                          <span>查看文件&nbsp;|&nbsp;{record.createdAt}</span> :
                                                          <span>创建文件&nbsp;|&nbsp;{record.createdAt}</span>
                                                  }

                                              </Col>
                                          </Row>
                                          {record.action == 'view' ?
                                              record.trace.map(item => {
                                                  return (
                                                      <span>{item.nickname}&nbsp; >&nbsp;</span>
                                                  )
                                              }) : null
                                          }
                                      </Timeline.Item>

                                  )
                              }) : ''
                          }
                      </Timeline>
                  </div>
          }
          </div>
    );
  }

}

ShareRecord.propTypes = {
  share: PropTypes.object.isRequired,
  form: PropTypes.object.isRequired,
};

const WrappedTabShared = Form.create({})(ShareRecord);
export default WrappedTabShared;
